﻿using System;
using TrafficArchives.DataAccess;

namespace TrafficArchives.Users
{
    /// <summary>
    /// 角色编辑。
    /// </summary>
    public partial class RoleEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Initlize();
            }
        }

        private void Initlize()
        {
            if (Request.QueryString["action"] == "edit"
                && !string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                LblTitle.InnerText = "修改角色";
                var id = Request.QueryString["id"];
                var db = new RoleDb();
                var data = db.GetData(id);
                if (data.Rows.Count > 0)
                {
                    TxtRoleName.Text = data.Rows[0]["rolename"].ToString();
                    RdoIsEnabled.SelectedIndex = data.Rows[0]["isvalis"].ToString() == "0" ? 0 : 1;
                    MenuString = data.Rows[0]["powerassemble"].ToString();
                }
            }
            else
            {
                MenuString = string.Empty;
                RdoIsEnabled.SelectedIndex = 1;
                LblTitle.InnerText = "新增角色";
            }
        }

        protected string MenuString { private set; get; }

        protected void BtnSaveClick(object sender, EventArgs e)
        {
            var db = new RoleDb();
            var menuString = Request.Form["menuString"];
            var isEdit = Request.QueryString["action"] == "edit" && !string.IsNullOrEmpty(Request.QueryString["id"]);
            var data = isEdit ? db.GetData(Request.QueryString["id"]) : db.GetNoneData();

            if (!isEdit)
            {
                var newRow = data.NewRow();
                newRow["userrole_id"] = Guid.NewGuid().ToString();
                data.Rows.Add(newRow);
            }
            data.Rows[0]["powerassemble"] = menuString;
            data.Rows[0]["rolename"] = TxtRoleName.Text;
            data.Rows[0]["createtime"] = DateTime.Now;
            data.Rows[0]["isvalis"] = RdoIsEnabled.SelectedIndex;

            if (isEdit)
            {
                db.Update(data);
            }
            else
            {
                db.Add(data);
            }
            Response.Redirect("RoleView.aspx");
        }
    }
}